﻿using System.Xml.Linq;

namespace StockAccessors.Interdin.Model
{
	internal class WebPage
	{
		#region Attributes

		private string _data;

		#endregion

		#region Public Methods

		public WebPage(string data)
		{
			_data = data;
		}

        protected XDocument CreateGroupXml(string id)
        {
            // Drop the unneeded part
            int startIndex = _data.IndexOf(string.Format(@"<tbody id='{0}'>", id), System.StringComparison.Ordinal);
            int endIndex = _data.IndexOf(@"</tbody>", startIndex, System.StringComparison.Ordinal);
            if (endIndex == -1)
            {
                endIndex = _data.IndexOf(@"</table>", startIndex, System.StringComparison.Ordinal); // Continuous market CFDs looks like broken
                _data = _data.Insert(endIndex, @"</tbody>");
            }
            
            string subPage = _data.Substring(startIndex, endIndex - startIndex + @"</tbody>".Length);

            subPage = this.FixXml(subPage);

            // Prepare as an xml document
            subPage = subPage.Insert(0, "<xml>\n");
            subPage += "\n</xml>";

            return XDocument.Parse(subPage);
        }

		#endregion

        #region Private Methods

        private string FixXml(string xmlData)
        {
            int startIndex = 0;

            do
            {
                startIndex = xmlData.IndexOf("<spacer", startIndex, System.StringComparison.Ordinal);
                if (startIndex != -1)
                {
                    startIndex = xmlData.IndexOf(">", startIndex, System.StringComparison.Ordinal);
                    xmlData = xmlData.Insert(startIndex, "/");
                }
            } while (startIndex != -1);

            
            return xmlData.Replace("&nbsp;"," ").Replace("&","and");
        }

        #endregion

    }
}
